import _ from 'lodash'
import { ref } from 'vue';
import {$bus, $utils} from '@jzl/utils'

export function useItemOps({
 currentItem,
 currentItems,
 elemNodes,
 currentItemElCode,
 projectId
}) {

  const isEditItem = ref(false);
  const hoverItemCode = ref(null);
  let leaveTimeout = null;

  const handleSelectItem = (data) => {
    isEditItem.value = true;
    currentItem.value = data.item;
    currentItems.value = data.items;

    let isSelectItem = data.isSelectItem;
    let targetEleName = data.targetEleName;

    if (!targetEleName && isSelectItem) {
      let itemCode = _.get(currentItem.value, "page_item_code");
      let itemNodeData = _.find(elemNodes.value, node => _.get(node, 'isRoot') && _.get(node, 'item.page_item_code') === itemCode);
      targetEleName = _.get(itemNodeData, 'code');
    }

    if (targetEleName) currentItemElCode.value = targetEleName;

    /*if ($refs.builderNodes?.showNodeActionPopover) {
      $refs.builderNodes.showNodeActionPopover();
    }*/
  };

  const getIndex = () => {
    let itemCode = _.get(currentItem.value, 'page_item_code');
    if (!itemCode) return -1;
    return _.findIndex(currentItems.value, { page_item_code: itemCode });
  };

  const moveUp = () => {
    let idx = getIndex();
    if (idx <= 0) return;
    let ci = currentItems.value.splice(idx, 1);
    currentItems.value.splice(idx - 1, 0, ci[0]);
  };

  const moveDown = () => {
    let idx = getIndex();
    if (idx < 0 || idx >= currentItems.value.length - 1) return;
    let ci = currentItems.value.splice(idx, 1);
    currentItems.value.splice(idx + 1, 0, ci[0]);
  };

  const copy = () => {
    let idx = getIndex();
    if (idx < 0) return;

    let orig = currentItems.value[idx];
    let code = $utils.getNanoid(10);
    let citem = _.defaultsDeep({
      page_item_code: code,
      alias: _getAlias(code),
      project_id: projectId.value,
      module_name: code,
      i: code
    }, orig);

    if (citem.options && citem.options.length) {
      for (let i = 0; i < citem.options.length; i++) {
        citem.options[i].fio_code = $utils.getNanoid(10);
      }
    }

    currentItems.value.splice(idx + 1, 0, citem);
    // updateMask();
    $bus.emit('design:refreshMask')
  };

  const handleItemEnter = (pageItemCode) => {
    hoverItemCode.value = pageItemCode;

    if(leaveTimeout) {
      clearTimeout(leaveTimeout)
      leaveTimeout = null
    }
  }

  const handleItemLeave = (pageItemCode) => {
    if(pageItemCode === hoverItemCode.value) {
      hoverItemCode.value = '';
    }

    // leaveTimeout = setTimeout(() => {
    //   $bus.emit('design:clearHoverMask')
    // }, 100)
  }

  return {
    isEditItem,
    hoverItemCode,

    handleSelectItem,
    getIndex,
    moveUp,
    moveDown,
    copy,
    handleItemEnter,
    handleItemLeave
  };
}
